<?php

namespace App\Admin\Actions;

use App\Models\User;
use Dcat\Admin\Grid\BatchAction;
use Illuminate\Http\Request;

class BatchEcpmFilter extends BatchAction
{
    protected $action;

    // 注意action的构造方法参数一定要给默认值
    public function __construct($title = null, $action = 1)
    {
        $this->title = $title;
        $this->action = $action;
    }

    // 确认弹窗信息
    public function confirm()
    {
        $remark = "启用";
        if (!$this->action) {
            $remark = "禁用";
        }
        return sprintf('您确定要%s已选中的用户广告展示吗？', $remark);
    }

    // 处理请求
    public function handle(Request $request)
    {
        $keys = $this->getKey();
        $action = $request->get('action');

        foreach (User::query()->find($keys) as $post) {
            $post->is_show_ad = intval($action);
            $post->save();
        }

        $message = $action ? '广告启用成功' : '广告禁用成功';

        return $this->response()->success($message)->refresh();
    }

    // 设置请求参数
    public function parameters()
    {
        return [
            'action' => $this->action,
        ];
    }
}
